

const METHOD = Object.freeze({
  GET: 'GET',
  POST: 'POST',
  PUT: 'PUT',
  DELETE: 'DELETE',
})
export {
  METHOD
}

const whiteList = [200, 201]
const baseURL = 'http://localhost:5173/api';



function appendParams(baseURL, options) {
  const { params } = options;
  if(!params) {
    return baseURL; 
  }

  const queryString = Object.keys(params)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
    .join('&');

  if (queryString) {
    return `${baseURL}?${queryString}`;
  } else {
    return baseURL;
  }
}

function request(options) {

  return new Promise((resolve, reject) => {
    uni.request({
      header: {
        'Content-Type': 'application/json'
      },
      ...options,
      url: appendParams(`${baseURL}${options.url}`, options),
      success: (response) => {
        if (whiteList.includes(response.statusCode)) {
          resolve(response.data);
        } else {
          reject(response);
        }
      },
      fail: (err) => {
        reject(err);
      }
    });
  });
}

export default request;